package com.hqd.ch03.v40.context.ui.support;

import com.hqd.ch03.v40.aware.BeanClassLoaderAware;
import com.hqd.ch03.v40.context.HierarchicalMessageSource;
import com.hqd.ch03.v40.context.MessageSource;
import com.hqd.ch03.v40.context.support.ResourceBundleMessageSource;
import com.hqd.ch03.v40.context.ui.HierarchicalThemeSource;
import com.hqd.ch03.v40.context.ui.Theme;
import com.hqd.ch03.v40.context.ui.ThemeSource;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ResourceBundleThemeSource implements HierarchicalThemeSource, BeanClassLoaderAware {

    private final Map<String, Theme> themeCache = new ConcurrentHashMap<>();

    private ThemeSource parentThemeSource;
    private String basenamePrefix = "";

    private String defaultEncoding;

    private Boolean fallbackToSystemLocale;

    private ClassLoader beanClassLoader;

    @Override
    public ThemeSource getParentThemeSource() {
        return this.parentThemeSource;
    }

    @Override
    public void setParentThemeSource(ThemeSource parent) {
        this.parentThemeSource = parent;

        // Update existing Theme objects.
        // Usually there shouldn't be any at the time of this call.
        synchronized (this.themeCache) {
            for (Theme theme : this.themeCache.values()) {
                initParent(theme);
            }
        }
    }

    /**
     * Set the prefix that gets applied to the ResourceBundle basenames,
     * i.e. the theme names.
     * E.g.: basenamePrefix="test.", themeName="theme" &rarr; basename="test.theme".
     * <p>Note that ResourceBundle names are effectively classpath locations: As a
     * consequence, the JDK's standard ResourceBundle treats dots as package separators.
     * This means that "test.theme" is effectively equivalent to "test/theme",
     * just like it is for programmatic {@code java.util.ResourceBundle} usage.
     *
     * @see java.util.ResourceBundle#getBundle(String)
     */
    public void setBasenamePrefix(String basenamePrefix) {
        this.basenamePrefix = (basenamePrefix != null ? basenamePrefix : "");
    }

    /**
     * Set the default charset to use for parsing resource bundle files.
     * <p>{@link ResourceBundleMessageSource}'s default is the
     * {@code java.util.ResourceBundle} default encoding: ISO-8859-1.
     *
     * @see ResourceBundleMessageSource#setDefaultEncoding
     * @since 4.2
     */
    public void setDefaultEncoding(String defaultEncoding) {
        this.defaultEncoding = defaultEncoding;
    }

    /**
     * Set whether to fall back to the system Locale if no files for a
     * specific Locale have been found.
     * <p>{@link ResourceBundleMessageSource}'s default is "true".
     *
     * @see ResourceBundleMessageSource#setFallbackToSystemLocale
     * @since 4.2
     */
    public void setFallbackToSystemLocale(boolean fallbackToSystemLocale) {
        this.fallbackToSystemLocale = fallbackToSystemLocale;
    }

    @Override
    public void setBeanClassLoader(ClassLoader beanClassLoader) {
        this.beanClassLoader = beanClassLoader;
    }


    /**
     * This implementation returns a SimpleTheme instance, holding a
     * ResourceBundle-based MessageSource whose basename corresponds to
     * the given theme name (prefixed by the configured "basenamePrefix").
     * <p>SimpleTheme instances are cached per theme name. Use a reloadable
     * MessageSource if themes should reflect changes to the underlying files.
     *
     * @see #setBasenamePrefix
     * @see #createMessageSource
     */
    @Override

    public Theme getTheme(String themeName) {
        Theme theme = this.themeCache.get(themeName);
        if (theme == null) {
            synchronized (this.themeCache) {
                theme = this.themeCache.get(themeName);
                if (theme == null) {
                    String basename = this.basenamePrefix + themeName;
                    MessageSource messageSource = createMessageSource(basename);
                    theme = new SimpleTheme(themeName, messageSource);
                    initParent(theme);
                    this.themeCache.put(themeName, theme);
                }
            }
        }
        return theme;
    }

    protected MessageSource createMessageSource(String basename) {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename(basename);
        if (this.defaultEncoding != null) {
            messageSource.setDefaultEncoding(this.defaultEncoding);
        }
        if (this.fallbackToSystemLocale != null) {
            messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale);
        }
        if (this.beanClassLoader != null) {
            messageSource.setBeanClassLoader(this.beanClassLoader);
        }
        return messageSource;
    }

    protected void initParent(Theme theme) {
        if (theme.getMessageSource() instanceof HierarchicalMessageSource) {
            HierarchicalMessageSource messageSource = (HierarchicalMessageSource) theme.getMessageSource();
            if (getParentThemeSource() != null && messageSource.getParentMessageSource() == null) {
                Theme parentTheme = getParentThemeSource().getTheme(theme.getName());
                if (parentTheme != null) {
                    messageSource.setParentMessageSource(parentTheme.getMessageSource());
                }
            }
        }
    }

}
